#!/usr/bin/env python
#!-*- coding:utf-8 -*-

from datetime import datetime, timedelta
from calendar import monthrange

def Days_Of_Month(year,month):
    """年,月の日数を返す"""
    return monthrange(year, month)[1]
    
def Get_FromTo(simebi, date_yyyymmdd):
    """
    締日を元に開始日、終了日をyyyymmdd文字列で戻す
    """
    if simebi == "":
        simebi = "31"
    
    date_str = date_yyyymmdd
    if date_str == "":
        today = datetime.today()
        date_str  = "%04d%02d%02d" % (today.year, today.month, today.day)
    #print date_str

    # 引数の年月日の年月に対する月末日を生成
    wk_dd = simebi
    try:
        wk_dt = datetime(int(date_str[0:4]), int(date_str[4:6]), int(wk_dd))
    except:
        # 例外になるってことは月末ってことじゃろ
        wk_dd = str(Days_Of_Month(int(date_str[0:4]), int(date_str[4:6])))

    matsu_yyyymmdd = "%04d%02d%02d" % (int(date_str[0:4]), int(date_str[4:6]), int(wk_dd))
    matsu_yyyymmdd_dt = datetime(int(matsu_yyyymmdd[0:4]), int(matsu_yyyymmdd[4:6]), int(wk_dd))
    
    start_yyyymmdd = "%04d%02d%02d"
    ended_yyyymmdd = "%04d%02d%02d"
    if matsu_yyyymmdd >= date_str:
        # 前月の基準日+1から今月の基準日
        if matsu_yyyymmdd_dt.month == 1:
            wk_dt = datetime(matsu_yyyymmdd_dt.year - 1, 12, int(simebi))
        else:
            try:
                wk_dt = datetime(matsu_yyyymmdd_dt.year, matsu_yyyymmdd_dt.month - 1, int(simebi))
            except:
                # 例外になるってことは月末ってことじゃろ
                dd_str = str(Days_Of_Month(matsu_yyyymmdd_dt.year, matsu_yyyymmdd_dt.month - 1))
                wk_dt = datetime(int(matsu_yyyymmdd[0:4]), int(matsu_yyyymmdd[4:6]) - 1, int(dd_str))

        wk_dt = wk_dt + timedelta(days=1)        
        start_yyyymmdd = start_yyyymmdd % (wk_dt.year, wk_dt.month, wk_dt.day)
        
        ended_yyyymmdd = matsu_yyyymmdd
        
    else:
        # 今月の基準日+1日から翌月の基準日
        wk_dt = datetime(int(matsu_yyyymmdd[0:4]), int(matsu_yyyymmdd[4:6]), int(simebi))
        wk_dt = wk_dt + timedelta(days=1)
        start_yyyymmdd = start_yyyymmdd % (wk_dt.year, wk_dt.month, wk_dt.day)
        
        if int(matsu_yyyymmdd[4:6]) == 12:
            wk_dt = datetime(int(matsu_yyyymmdd[0:4]) + 1, 1, int(simebi))
        else:
            wk_dt = datetime(int(matsu_yyyymmdd[0:4]), int(matsu_yyyymmdd[4:6]) + 1, int(simebi))
        ended_yyyymmdd = ended_yyyymmdd % (wk_dt.year, wk_dt.month, wk_dt.day)

    return start_yyyymmdd, ended_yyyymmdd


print Get_FromTo("5", "20100531")
